package com.cfets.annualAssessment.securityConfig;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * Created by ShenYiChou on 2017/10/23.
 */
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private String defaultFailureUrl;
    private String FailureUrl;
    public MyAuthenticationFailureHandler() {
    }

    public MyAuthenticationFailureHandler(String defaultFailureUrl) {
        this.setDefaultFailureUrl(defaultFailureUrl);
        this.FailureUrl = "";
    }
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if(this.defaultFailureUrl == null) {
            this.logger.debug("No failure URL set, sending 401 Unauthorized error");
            response.sendError(401, "Authentication Failed: " + exception.getMessage());
        } else {
            this.saveException(request, exception);
            if(exception.getMessage().equals("verifyCode is wrong")) {
                this.FailureUrl = this.defaultFailureUrl +"=1";//验证码错误
//                request.setAttribute("AnnualLoginError","1");
            }else{
                this.FailureUrl = this.defaultFailureUrl +"=2";//用户名密码错误
//                request.setAttribute("AnnualLoginError","2");
            }
            this.logger.debug("Redirecting to " + this.FailureUrl);
            super.getRedirectStrategy().sendRedirect(request, response, this.FailureUrl);
//            request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response);

        }

    }

    public void setDefaultFailureUrl(String defaultFailureUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl), "\'" + defaultFailureUrl + "\' is not a valid redirect URL");
        this.defaultFailureUrl = defaultFailureUrl;
    }
}
